/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.ThanhVienDAO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Thanhvien;

/**
 *
 * @author HoangLiem
 */
@WebServlet(name = "xuLyDangNhap", urlPatterns = {"/xuLyDangNhap"})
public class xuLyDangNhap extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        Thanhvien tv = new Thanhvien();
        String username = request.getParameter("textboxTenDn");
        String password = request.getParameter("textboxDn");
        String checkbox = "";
        if (request.getParameter("acceptCookieCheckbox") != null) {
            checkbox = request.getParameter("acceptCookieCheckbox");
        }
        tv = ThanhVienDAO.logIn(username, password);
        if (tv != null) {
            String outdate = ThanhVienDAO.IsBanUser(tv.getTenDangNhap());
            if (outdate.equals("")) {
                String tenDN = "";
                String matKhau = "";
                tenDN = session.getAttribute("tendn").toString();
                matKhau = session.getAttribute("matkhau").toString();
                if (checkbox.equals("checked")) {
                    Cookie cookieUserName = new Cookie("username", username);
                    cookieUserName.setMaxAge(365 * 24 * 60 * 60);
                    Cookie cookiePass = new Cookie("password", password);
                    cookiePass.setMaxAge(365 * 24 * 60 * 60);
                    response.addCookie(cookiePass);
                    response.addCookie(cookieUserName);
                }
                session.setAttribute("user", tv);
                response.sendRedirect("index.jsp");
            } else {
                String url = "loibanneduser.jsp";
                RequestDispatcher rd = request.getRequestDispatcher(url);
                request.setAttribute("outdate", outdate);
                rd.forward(request, response);
            }
        } else {
            response.sendRedirect("thongBaoLoi.jsp");
        }
    }
}
